package com.cenntro.oss.interceptor;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

//@EnableWebMvc
@Configuration
public class CustomWebMvcConfigurerAdapter implements WebMvcConfigurer {

	@Autowired
	private MyInterceptor myInterceptor;
	@Bean
    public MyInterceptor myInterceptor(){
//		if (myInterceptor == null){
//			synchronized (myInterceptor) {
//				if (myInterceptor == null){
//					myInterceptor = new MyInterceptor();
//				}
//			}
//		}
		return new MyInterceptor();
    }

	
	@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/*/**").addPathPatterns("/**/swagger-ui.html").excludePathPatterns("/upload/**").excludePathPatterns("/**/login").excludePathPatterns("/**/loginOut");  //对来自/user/** 这个链接来的请求进行拦截
//        registry.addInterceptor(myInterceptor()).addPathPatterns("/**/swagger-ui.html");
        registry.addInterceptor(localeChangeInterceptor());
	}
	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String os = System.getProperty("os.name").toLowerCase();
		if (os.toLowerCase().indexOf("window") >= 0){
			registry.addResourceHandler("/upload/**").addResourceLocations("file:///opt/data/upload/");  
		}else {
			registry.addResourceHandler("/upload/**").addResourceLocations("file:///opt/data/upload/");
		}
		
	}
	
    /**
     * 跨域支持
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600 * 24);
    }
	/**
	 * 
	 * 国际化默认语言
	 */
	@Bean
	public LocaleResolver localeResolver() {
		SessionLocaleResolver slr = new SessionLocaleResolver();
		slr.setDefaultLocale(Locale.US);
		return slr;
	}

	/**
	 * ?lang=en_US
	 * 修改默认配置，lang
	 */
	@Bean
	public LocaleChangeInterceptor localeChangeInterceptor() {
		LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
		lci.setParamName("lang");
		return lci;
	}
	
}
